import express from 'express';
import path from 'path';
import { captureScreenshot } from './helper/capture.js';

const cwd = process.cwd()
const app = express()

app.use(express.json())

app.get("/img/:name", (req, res) => {
    let name = req.params.name
    res.sendFile(path.join(cwd, 'images', name))
})

// 'blue' | 'pink' | 'purple' | 'green' | 'yellow' | 'gray' | 'red' | 'indigo' | 'SpringGradientWave'
app.post('/api/v1/md2jpeg', async (req, res) => {
    let config = req.body
    if (!config.content) {
        res.json({
            code: 400,
            msg: 'content is required'
        })
        return;
    }

    // 获取请求的域名
    const requestHost = req.headers.host;
    const protocol = req.protocol;
    const baseUrl = `${protocol}://${requestHost}`;
    
    try {
      const out = await captureScreenshot(config)
      console.log("image saved at", out.screenshotPath)

      if (config.type == 'file') {
        res.download(out.screenshotPath, out.filename)
        return;
      }
      res.json({
        code: 200,
        data: `${baseUrl}/img/${out.filename}`
      })
    } catch(error) {
      res.json({
        code: 500,
        msg: error.message
      })
    }
})

app.listen(13000, () => {
    console.log("server start at http://localhost:13000")
})
